package com.jinlejia.erp.ui.customer;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.PoiSearchAdapter;
import com.jinlejia.erp.bean.MeetPlaceBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityPoiSearchBinding;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class PoiSearchActivity extends AppCompatActivity implements
        OnGetPoiSearchResultListener, OnGetSuggestionResultListener  {

    private SuggestionSearch mSuggestionSearch = null;
    private ArrayList<Map<String,Object>> dataList = new ArrayList<>();
    private PoiSearchAdapter adapter;
    public String place;

    private ActivityPoiSearchBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_poi_search);
        binding.btBack.setOnClickListener(this::onClick);
        binding.yfRecycler.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PoiSearchAdapter(dataList,binding.etSearchText.getText().toString());
        adapter.changeMode(YfListMode.MODE_EMPTY);
        binding.yfRecycler.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        binding.yfRecycler.setAdapter(adapter);


        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        binding.etSearchText.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }

                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(getIntent().getStringExtra("city")));
            }
        });
        adapter.setOnItemClickListener((view, o) -> {
            Map<String,String> map = new HashMap<String, String>();
            place = ((HashMap<String,Object>)o).get("name").toString();
            map.put("place",place);
            map.put("property",getIntent().getStringExtra("property"));
            map.put("city",getIntent().getStringExtra("city"));

            //保存见面地点
            MeetPlaceBean mpb = new MeetPlaceBean();
            if( ((HashMap<String,Object>)o).containsKey("address") )
            mpb.setAddress(((HashMap<String,Object>)o).get("address").toString());
            mpb.setName(place);
            mpb.setCity(getIntent().getStringExtra("city"));

            ArrayList<MeetPlaceBean> shbList = DbUtil.getDB(PoiSearchActivity.this).single().query(MeetPlaceBean.class);
            if (shbList.size() == 10) {
                //数量达到20，删除第一个
                DbUtil.getDB(PoiSearchActivity.this).single().delete(shbList.get(0));
            }
            if (DbUtil.getDB(PoiSearchActivity.this).single().query(new QueryBuilder<>(MeetPlaceBean.class)
                    .whereEquals("address", mpb.getAddress())).size() > 0)
                //已经存在，先删除再存
                DbUtil.getDB(PoiSearchActivity.this).single().delete(WhereBuilder.create(MeetPlaceBean.class, "address=?", new String[]{mpb.getAddress()}));
            DbUtil.getDB(PoiSearchActivity.this).single().save(mpb);

            EventBus.getDefault().post(map,"TAG_PLACE_NAME");
            finish();
        });
    }

    public void onClick(View view) {
        finish();
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        dataList.clear();
        if (res == null || res.getAllSuggestions() == null) {
            adapter.changeMode(YfListMode.MODE_EMPTY);
            return;
        }
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null) {
                HashMap<String,Object> map = new HashMap<>();
                map.put( "name",info.key );
                map.put("LatLng",info.pt);
                dataList.add(map);
            }
        }
        if( dataList.size()>0 ) {
            adapter.setData(dataList);
            adapter.setWord(binding.etSearchText.getText().toString());
        }else{
            adapter.changeMode(YfListMode.MODE_EMPTY);
        }
        binding.yfRecycler.setAdapter(adapter);
    }
}
